﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Runtime.InteropServices;
using System.IO;
using System.Xml;
using System.Xml.Linq;


namespace JsonForm
{
    public partial class Form1 : XtraForm
    {
        public Form1()
        {
            InitializeComponent();
            InitGrid();

        }
        BindingList<Person> gridDataList = new BindingList<Person>();
        void InitGrid()
        {
    
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var paramx = new
            {
                key1 = "hello",
                key2 = "I don't nonw",
                data = new
                {
                    custom1="111a",
                    name = "2",
                }
            };
            String s1=JsonConvert.SerializeObject(paramx);
            var p2=JsonConvert.DeserializeObject(s1);

            var J1 = JObject.Parse(s1);

            System.Diagnostics.Debug.WriteLine(J1["data"]["custom1"]);


        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            var zz = new { };
            var z = new JObject();
            z["version"] = "123";
            String s1 = JsonConvert.SerializeObject(z);
            System.Diagnostics.Debug.WriteLine(z);

        }

        private const int LocaleSystemDefault = 0x0800;
        private const int LcmapSimplifiedChinese = 0x02000000;
        private const int LcmapTraditionalChinese = 0x04000000;

        [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int LCMapString(int locale, int dwMapFlags, string lpSrcStr, int cchSrc,
                                              [Out] string lpDestStr, int cchDest);

        public static string ToTranditionalChinese(string argSource)
        {
            var t = new String(' ', argSource.Length);
            LCMapString(LocaleSystemDefault, LcmapTraditionalChinese, argSource, argSource.Length, t, argSource.Length);
            return t;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            String data = File.ReadAllText(@"D:\project\五術\data\month\1995-9.xml", Encoding.UTF8);
            data = ToTranditionalChinese(data);
            File.WriteAllText(@"D:\project\五術\data\month\1995-9.tc.xml", data, Encoding.UTF8);
        }

        protected String justReplace(String s1)
        {
            String[] from={"零","一","二","三","四","五","六","七","八","九"};
            String[] to={"0","1","2","3","4","5","6","7","8","9"};
            for(int i=0;i<10;i++)
            {
                s1=s1.Replace(from[i],to[i]);
            }
            return s1;
        }
        protected int replaceMonth(String s)
        {
            if (s.Equals("正"))
                return 1;
            String[] from={"一","二","三","四","五","六","七","八","九","十","十一","十二"};
            if(s.Length==0)
                return 0;
            int[] to={1,2,3,4,5,6,7,8,9,10,11,12};
            for(int i=0;i<12;i++)
            {
                if(s.Equals(from[i]))
                    return to[i];
            }
            throw new  Exception("No Match!"+s);
        }
        protected int replaceDay(String s)
        {
            int result=0;
            if(s.StartsWith("初"))
            {
                result=replaceMonth(s.Substring(1));
            }
            if(s.StartsWith("十"))
            {
                result=10+replaceMonth(s.Substring(1));
            }
            if(s.StartsWith("廿"))
            {
                result=20+replaceMonth(s.Substring(1));
            }
            if(s.StartsWith("三十"))
            {
                result=30+replaceMonth(s.Substring(2));
            }
            return result;
        }
        protected bool  processLunar(String s,ref int[] result)
        {
            bool lun=false;
            s = s.Trim();
            String[] ss=s.Split(' ');
            String s1=ss[0];
            String s2=ss[1];
            String s3=ss[2];
            s1=s1.Replace("年","");
            s1=justReplace(s1);
            int y=int.Parse(s1);

            s2=s2.Replace("月","");
            if(s2.Contains("閏"))
            {
                lun=true;
                s2=s2.Replace("閏","");
            }
            int m=replaceMonth(s2);

            int d = replaceDay(s3);

            result[0] = y;
            result[1] = m;
            result[2] = d;
            return lun;
        }
        protected int[] dateToNumber(String s)
        {
            DateTime d=DateTime.Parse(s);
            int[] r={d.Year,d.Month,d.Day};
            return r;                
        }
        protected String processXML(String fileName)
        {
            String data = File.ReadAllText(fileName);
            data=ToTranditionalChinese(data);
            XDocument doc=XDocument.Parse(data);

            var days = doc.Document.Root;
            Dictionary<string, Object> dd = new Dictionary<string, object>();

            foreach (var day in days.Elements())
            {
                String v = day.Attribute("date").Value;
                String dates=day.Element("date").Value;
                String gjy = day.Element("GJ_year").Value;
                String gjm = day.Element("GJ_month").Value;
                String gjd = day.Element("GJ_day").Value;
                String lunar = day.Element("lunar").Value;
                String yes = day.Element("yes").Value;
                String no  = day.Element("no").Value;

                yes = yes.Trim();
                String[] yess=yes.Split(' ');
                int[] dn=dateToNumber(dates);
                no = no.Trim();
                String[] nos = no.Split(' ');
                int [] lunarday={0,0,0};
                bool islun=false;
                islun = processLunar(lunar, ref lunarday);
                var j = new JObject();
                if (islun)
                {
                    var zz = new
                    {
                        date = dates,
                        dn = dn,
                        gj = new String[] { gjy, gjm, gjd },
                        lunar = lunarday,
                        intercalary = 1,
                        suitable = yess,
                        prohibit = nos
                    };
                    dd.Add(dates, zz);                    
                }
                else
                {
                    var zz = new
                    {
                        date = dates,
                        dn = dn,
                        gj = new String[] { gjy, gjm, gjd },
                        lunar = lunarday,
                        suitable = yess,
                        prohibit = nos
                        
                    };
                    dd.Add(dates, zz);
                }
            }
            String rs = JsonConvert.SerializeObject(dd, Newtonsoft.Json.Formatting.Indented);
            return rs;
        }
        private void button5_Click(object sender, EventArgs e)
        {
            String fileName=@"D:\project\五術\data\month\1995-9.xml";
            String f = Path.GetFileName(fileName);
            String p = Path.GetDirectoryName(fileName);
            String content=processXML(fileName);
            f=f.Replace(".xml", ".json");
            String fn = p + "\\" + f;
            File.WriteAllText(fn, content, Encoding.UTF8);

        }

        protected void convertToJson(String fileName)
        {
            if (fileName.EndsWith(".xml") == false)
                return;
            String fne=Path.GetFileName(fileName);
            String path = Path.GetDirectoryName(fileName);
            String fn = Path.GetFileNameWithoutExtension(fileName);
            String target = path + "\\" + fn + ".json";
            if (File.Exists(target))
                return;
            System.Diagnostics.Debug.WriteLine(fn);
            String content=processXML(fileName);
            File.WriteAllText(target, content, Encoding.UTF8);
        }
        private void button6_Click(object sender, EventArgs e)
        {
            String path1 = @"D:\project\五術\data\month\";
            String[] ss=Directory.GetFiles(path1);
            foreach (String s in ss)
            {
                convertToJson(s);
            }


        }

        private void button7_Click(object sender, EventArgs e)
        {
            String fn=@"D:\project\五術\data\month\1999-10.json";
            String content=File.ReadAllText(fn,Encoding.UTF8);
            Dictionary<String, JObject> ms=JsonConvert.DeserializeObject<Dictionary<String, JObject>>(content);
            foreach (String k in ms.Keys)
            {
                var o = ms[k];
                String s1=o["date"].Value<String>();
                String gjy=o["gj"][0].Value<String>();
                String gjm = o["gj"][1].Value<String>();
                String gjd = o["gj"][2].Value<String>();

                int y=o["lunar"][0].Value<int>();
                int m = o["lunar"][1].Value<int>();
                int d = o["lunar"][2].Value<int>();
                var s2 = o["subitable"].Values();
                foreach (var it in s2)
                {
                    if (it.Type == JTokenType.String)
                    {
                        String s3=it.Value<String>();
                    }
                }
                if (o["NoExist"].HasValues)
                {

                }

            }

            
            
        }

        private void button8_Click(object sender, EventArgs e)
        {
            String path1 = @"D:\project\五術\data\jachi\";
            String[] ss = Directory.GetFiles(path1);
            foreach (String s in ss)
            {
                convertToJachiJson(s);
            }
        }

        private void convertToJachiJson(string fileName)
        {
            if (fileName.EndsWith(".xml") == false)
                return;
            String fne = Path.GetFileName(fileName);
            String path = Path.GetDirectoryName(fileName);
            String fn = Path.GetFileNameWithoutExtension(fileName);
            String target = path + "\\" + fn + ".json";
            if (File.Exists(target))
                return;
            System.Diagnostics.Debug.WriteLine(fn);
            String content = processJachiXML(fileName);
            File.WriteAllText(target, content, Encoding.UTF8);
        }

        private string processJachiXML(string fileName)
        {
            String data = File.ReadAllText(fileName);
            data = ToTranditionalChinese(data);
            XDocument doc = XDocument.Parse(data);

            var jachis = doc.Document.Root;
            Dictionary<string, Object> dd = new Dictionary<string, object>();
            foreach (var jachi in jachis.Elements("jachi"))
            {
                String name = jachi.Element("name").Value;
                String id = jachi.Element("id").Value;
                String ty = jachi.Element("type").Value;
                String time = jachi.Element("time").Value;
                DateTime dt= DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss",null);
                String t2=dt.ToString("yyyy/MM/dd HH:mm:ss");
                var entry = new
                {
                    name=name,
                    id=id,
                    type=ty,
                    time=dt,
                    times=t2
                };
                dd.Add(name, entry);
            }
            String rs = JsonConvert.SerializeObject(dd, Newtonsoft.Json.Formatting.Indented);
            return rs;
        }
        

    }
}